package main

import (
	"fmt"
	"io/ioutil"
	"io"
	"os"

	// "net/http"
	"github.com/labstack/echo"
	// "github.com/labstack/echo/middleware"
)

func upload(c echo.Context) error {
	// Read form fields
	name := c.FormValue("productid")

	//-----------
	// Read file
	//-----------
	// Source
	_dir := "/home/vantian/data/"+name
    exist, err := PathExists(_dir)
    if err != nil {
        fmt.Printf("get dir error![%v]\n", err)
        return err
    }

    if exist {
        fmt.Printf("has dir![%v]\n", _dir)
    } else {
        fmt.Printf("no dir![%v]\n", _dir)
        // 创建文件夹
        err := os.Mkdir(_dir, os.ModePerm)
        if err != nil {
            fmt.Printf("mkdir failed![%v]\n", err)
        } else {
            fmt.Printf("mkdir success!\n")
        }
    }

	file, err := c.FormFile("file")
	if err != nil {
		return err
	}
	src, err := file.Open()
	if err != nil {
		return err
	}
	defer src.Close()

	// Destination
	dst, err := os.Create(_dir+"/"+file.Filename)
	if err != nil {
		return err
	}
	defer dst.Close()
	contentByte, err := ioutil.ReadAll(dst)
		if err != nil {
			fmt.Println("read file err")
			return err
		}
		_, err = dst.Write(contentByte)
		if err != nil {
			fmt.Println("Write file err")
			return err
		}
	// Copy
	if _, err = io.Copy(dst, src); err != nil {
		return err
	}
	c.JSON(200, map[string]interface{}{
		"msg":   "success",
		"data":string(name+"/"+file.Filename),
	})
	return nil
}
func PathExists(path string) (bool, error) {
    _, err := os.Stat(path)
    if err == nil {
        return true, nil
    }
    if os.IsNotExist(err) {
        return false, nil
    }
    return false, err
}

func main() {
	e := echo.New()

	// e.Use(middleware.Logger())
	// e.Use(middleware.Recover())

	e.Static("/", "public")
	e.POST("/upload", upload)

	e.Logger.Fatal(e.Start(":9300"))
}